class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(k, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                if(Math.abs(o2-x) == Math.abs(o1-x)){
                    return o2-o1;
                }
                return Math.abs(o2-x) - Math.abs(o1-x);
            }
        });
        for (int i = 0; i < arr.length; i++) {
            if(maxHeap.size() < k){
                maxHeap.offer(arr[i]);
            }else{
                int value = maxHeap.peek();
                if(Math.abs(arr[i]-x) < Math.abs(value-x)||(Math.abs(arr[i]-x) == Math.abs(value-x) && arr[i] < value)){
                    maxHeap.poll();
                    maxHeap.offer(arr[i]);
                }
            }
        }

        PriorityQueue<Integer> minHeap = new PriorityQueue();
        while(maxHeap.size() > 0){
            minHeap.offer(maxHeap.poll());
        }


        ArrayList<Integer> list = new ArrayList<>();
        while(minHeap.size() > 0){
            list.add(minHeap.poll());
        }
        return list;
    }
}